package com.xiaoming.backend.controller;

import com.xiaoming.backend.dto.request.WareHouseRequest;
import com.xiaoming.backend.dto.response.WareHouseResponse;
import com.xiaoming.backend.entity.orm.User;
import com.xiaoming.backend.result.exception.AppErrorException;
import com.xiaoming.backend.result.exception.error.AppError;
import com.xiaoming.backend.service.IWareHouseService;
import com.xiaoming.backend.util.JsonUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/warehouse")
@RequiredArgsConstructor
@PreAuthorize("@securityService.checkInstitution(#institutionId)")
@Tag(name = "WareHouseComtroller", description = "仓库接口")
public class WareHouseComtroller {
    private final IWareHouseService wareHouseService;

    @GetMapping("/find")
    @Operation(summary = "findWareHouse", description = "获取仓库")
    public ResponseEntity<?> findWareHouse(){
        String jsonStr = "";
        try {
            // 从认证信息中提取 User 对象（需类型转换）
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            List<WareHouseResponse> wareHouse = wareHouseService.findWareHouse(user);
            jsonStr = JsonUtil.objToJson(wareHouse);
        }catch (AppErrorException e){
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getErrorMsg());
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(AppError.TOKEN_ERROR.getErrorMsg());
        }
        return ResponseEntity.ok(jsonStr);
    }

    @PutMapping("/upt")
    @Operation(summary = "uptWareHouse", description = "更新仓库")
    public ResponseEntity<?> uptWareHouse(@RequestBody WareHouseRequest wareHouseRequest){
        try {
            // 从认证信息中提取 User 对象（需类型转换）
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            wareHouseService.updWareHouse(wareHouseRequest);
        }catch (AppErrorException e){
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getErrorMsg());
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(AppError.TOKEN_ERROR.getErrorMsg());
        }
        return ResponseEntity.ok("成功");
    }
}
